package com.zm.xiaohashu.count.biz.consumer.db;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.zm.xiaohashu.count.biz.constant.MQConstants;
import com.zm.xiaohashu.count.biz.mapper.NoteCountMapper;
import com.zm.xiaohashu.count.biz.mapper.UserCountMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(consumerGroup = "xiaohashu_group_" + MQConstants.TOPIC_USER_LIKE_OR_UNLIKE_2_DB, // Group 组
        topic = MQConstants.TOPIC_USER_LIKE_OR_UNLIKE_2_DB // 主题 Topic
)
@Slf4j
public class CountUserLikeUnlike2DBConsumer implements RocketMQListener<String> {
    @Resource
    private UserCountMapper userCountMapper;
    private RateLimiter rateLimiter = RateLimiter.create(5000);

    @Override
    public void onMessage(String body) {
        rateLimiter.acquire();
        log.info("## 消费到了 MQ 【用户维度:计数: 点赞数/取消点赞数】, {}...", body);
        Map<String, Integer> countMap = null;
        try {
            countMap = JSONUtil.toBean(body, Map.class);
        } catch (Exception e) {
            log.error("## 解析 JSON 字符串异常", e);
        }
        if (CollUtil.isNotEmpty(countMap)) {
            // 批量插入或更新
            countMap.forEach((k, v) -> {
                userCountMapper.insertOrUpdateByNote(v, Long.parseLong(k));
            });
        }

    }
}
